package com.utils.wechat;

import com.bean.WebsiteUserInfo;
import com.bean.wechat.ResultInfo;
import com.bean.wechat.WechatWebsite;
import com.mapper.mysql.UserInfoMapper;
import com.mapper.repository.mysql.WechatWebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@Service
public class WechatStrategyBind implements WechatStrategy  {

    //解决绑定问题
    //map是输入
    /**
     *
     * @param resultInfo  返回的结果
     * @param content     请求的内容
     */

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WechatWebsiteRepository wechatWebsiteRepository;

    @Override
    public void returnMsg(ResultInfo resultInfo,String content) {

        // 正则表达式（根据需求调整）
        String regex = "^绑定.+:.+$";
        if(!content.matches(regex)){
            resultInfo.setReturnMethod("text");
            resultInfo.setContent("绑定的格式错误，请输入绑定XXX:XXX");
            return;
        }

        //判断用户名密码是否正确
        String username = content.substring("绑定".length()).split(":")[0];
        String password = content.substring("绑定".length()).split(":")[1];
        WebsiteUserInfo userInfo = new WebsiteUserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        WebsiteUserInfo db = userInfoMapper.selectOne(userInfo);
        if(db==null){
            resultInfo.setReturnMethod("text");
            resultInfo.setContent("绑定失败：用户名或密码错误");

        }else{
            //判断是否已绑定
            WechatWebsite wechatWebsite = wechatWebsiteRepository.findByWebsiteuserid(db.getId());
            if(wechatWebsite!=null){
                resultInfo.setReturnMethod("text");
                resultInfo.setContent(db.getUsername()+"已绑定");
            }else{
                resultInfo.setReturnMethod("text");

                //否则绑定
                wechatWebsite = new WechatWebsite();
                wechatWebsite.setId(UUID.randomUUID().toString());
                wechatWebsite.setWebsiteuserid(db.getId());
                wechatWebsite.setWechatid(resultInfo.getToUserName());
                wechatWebsite.setCreatetime(LocalDateTime.now());
                wechatWebsiteRepository.save(wechatWebsite);
                resultInfo.setContent(db.getUsername()+"绑定成功");
            }
        }
    }

}
